package com.baichang.taoshunda.service.impl;

import com.alipay.api.AppPay;
import com.baichang.framework.Constant;
import com.baichang.framework.excelption.ServiceException;
import com.baichang.framework.model.Page;
import com.baichang.framework.utils.KidUtils;
import com.baichang.framework.utils.MD5Util;
import com.baichang.framework.utils.RedisUtil;
import com.baichang.framework.utils.TokenUtils;
import com.baichang.taoshunda.dao.DeliveryClerkDao;
import com.baichang.taoshunda.entity.DeliveryClerk;
import com.baichang.taoshunda.service.*;
import com.baichang.taoshunda.utils.DeliveryUtils;
import com.google.common.base.Optional;
import com.weixin.pay.api.WeixinPay;
import com.weixin.pay.api.model.PayInfo;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Administrator on 2017/8/22 0022.
 */
@Service
public class DeliveryClerkServiceImpl implements DeliveryClerkService {

    @Autowired
    private DeliveryClerkDao deliveryClerkDao;
    @Autowired
    private DeliveryMsgService deliveryMsgService;

    @Autowired
    private OrderService orderService;

    @Autowired
    TrendService trendService;

    @Autowired
    private ParamsService paramsService;

    /**
     * 查询配送人员列表
     *
     * @param name
     * @param lastTime
     * @param created
     * @param cityId
     * @param nowPage
     * @param pageSize @return
     */
    @Override
    public Page queryDispatcherList(String name, String lastTime, String created, Integer cityId, int nowPage, int pageSize) {
        return deliveryClerkDao.queryDispatcherList(name, lastTime, created, cityId, nowPage, pageSize);
    }

    /**
     * 查询配送员订单
     *
     * @param id
     * @param nowPage
     * @param pageSize @return
     */
    @Override
    public Page<Map<String, Object>> dispatcherOrder(Integer id, int nowPage, int pageSize) {
        return deliveryClerkDao.dispatcherOrder(id, nowPage, pageSize);
    }

    /**
     * 查询配送员明细
     *
     * @param id
     * @param nowPage
     * @param pageSize @return
     */
    @Override
    public Page<Map<String, Object>> dispatcherOrderDetails(Integer id, int nowPage, int pageSize) {
        return deliveryClerkDao.dispatcherOrderDetails(id, nowPage, pageSize);
    }

    /**
     * 根据编号获取配送员信息
     *
     * @param id 编号
     * @return
     */
    @Override
    public DeliveryClerk getDeliveryClerkById(Integer id) throws ServiceException {
        DeliveryClerk deliveryClerk = deliveryClerkDao.getEntityById(id);
        if (deliveryClerk == null) {
            throw new ServiceException("配送员不存在");
        }
        return deliveryClerk;
    }

    /**
     * 修改配送员信息
     *
     * @param id
     * @param account
     * @param name
     * @param address
     * @param headPic
     * @param provincesId
     * @param cityId
     * @param areaId
     * @return
     */
    @Override
    public int updateDispatcherInfo(Integer id, String account, String name, String address, String headPic, Integer provincesId, Integer cityId, Integer areaId) {
        Map map = new HashedMap();
        map.put("account", account);
        map.put("name", name);
        map.put("address", address);
        map.put("headPic", headPic);
        map.put("provinceId", provincesId);
        map.put("cityId", cityId);
        map.put("areaId", areaId);
        return deliveryClerkDao.update(map, id);
    }

    /**
     * 配送员启用、禁用
     *
     * @param id
     * @param state
     * @return
     */
    @Override
    public int updateState(Integer id, Integer state) throws ServiceException {
//        //查询当前配送中的订单
//        int orderCount = orderService.getOrderCountByDeliveryId(id);
//        if (orderCount > 0) {
//            throw new ServiceException("该配送员存在配送中订单！");
//        }
//        if (state == 2) {
//            DeliveryClerk deliveryClerk = deliveryClerkDao.getEntityById(id);
//            UserJPushHelper jPushHelper = new UserJPushHelper("distribution.properties");
//            jPushHelper.sendMsgByAlias(Message.newBuilder().setMsgContent("").build(), deliveryClerk.getAccount());
//        }

        return deliveryClerkDao.updateState(id, state);
    }

    /**
     * 重置配送员密码
     *
     * @param id
     * @param pwd
     * @return
     */
    @Override
    public int resetPassword(Integer id, String pwd) {
        String md5 = MD5Util.md5(pwd);
        return deliveryClerkDao.resetPassword(id, md5);
    }

    /**
     * 配送人员手机号登录
     *
     * @param mobile 手机号
     * @param code   密码
     * @return
     */
    @Override
    public Map<String, Object> mobileMsgLogin(String mobile, String code) throws ServiceException {
        //1.判断手机号
        if (StringUtils.isEmpty(mobile)) {
            throw new ServiceException("手机号不能为空");
        }
        //2.判断是否发送验证码
        String redisCode = RedisUtil.get(Constant.SESSION_CODE_KEY + mobile);
        if (StringUtils.isEmpty(redisCode)) {
            throw new ServiceException("尚未发送验证码");
        }
        //3.判断验证码是否正确
        if (!code.equals(redisCode)) {
            throw new ServiceException("验证码不正确");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        DeliveryClerk deliveryClerk = deliveryClerkDao.getDeliveryByPhone(mobile);
        if (deliveryClerk == null) {
            throw new ServiceException("配送员不存在");
        }
        map.put("id", deliveryClerk.getId());
        map.put("isAuth", deliveryClerk.getIsCertificate());
        map.put("isCertification", deliveryClerk.getIsCertification());
        map.put("cityId", deliveryClerk.getCityId());
        map.put("isOpen", deliveryClerk.getIsOpen());
        String token = TokenUtils.putValue(deliveryClerk.toMap(), 30);
        map.put("token", token);
        deliveryClerkDao.updateLastLoginDate(deliveryClerk.getId());
        //环信
//        map.put("hxName", bussiness.getHxName());
//        map.put("hxName", bussiness.getHxPwd());
        return map;
    }

    /**
     * 账号登录
     *
     * @param account 账号
     * @param pwd     密码
     * @return
     */
    @Override
    public Map<String, Object> accountLogin(String account, String pwd) throws ServiceException {
        //1.判断手机号
        if (StringUtils.isEmpty(account)) {
            throw new ServiceException("手机号不能为空");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        DeliveryClerk deliveryClerk = deliveryClerkDao.getDeliveryByPhone(account);
        String tel = paramsService.getParamsValue(21, 14).get("value").toString();
        if (deliveryClerk == null) {
            throw new ServiceException("您被删除或者禁用，如有疑问请联系客服！电话：" + tel);
        }
        if (!deliveryClerk.getPwd().equals(MD5Util.md5(pwd))) {
            throw new ServiceException("密码不正确");
        }
        map.put("id", deliveryClerk.getId());
        map.put("isAuth", deliveryClerk.getIsCertificate());
        map.put("isOpen", deliveryClerk.getIsOpen());
        map.put("cityId", deliveryClerk.getCityId());
        String token = TokenUtils.putValue(deliveryClerk.toMap(), 30);
        map.put("token", token);
        Map<String, Object> value = paramsService.getParamsValue(39, 39);
        double bailMoney = Double.parseDouble(value.get("value").toString());
        map.put("bailMoney", bailMoney);
        map.put("isPayment", deliveryClerk.getIsPayment());
        map.put("deliveryBail", deliveryClerk.getBail());
        deliveryClerkDao.updateLastLoginDate(deliveryClerk.getId());
        return map;
    }

    /**
     * 注册
     *
     * @param account         账号
     * @param code            验证码
     * @param pwd             密码
     * @param name            名称
     * @param area            地区
     * @param address         地址
     * @param cityId          城市编号
     * @param identityCardNum 身份证号
     * @param handheldPhotos  手持身份证
     * @param fontCard        身份证正面
     * @param reverseCrad     身份证反面
     */
    @Override
    public Map<String, Object> register(String account, String code, String pwd, String name, String area, String address, Integer cityId, String identityCardNum, String handheldPhotos, String fontCard, String reverseCrad) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        DeliveryClerk deliveryClerk = deliveryClerkDao.getDeliveryByPhone(account);
        if (deliveryClerk != null) {
            throw new ServiceException("该手机号已被注册");
        }
        deliveryClerk = new DeliveryClerk();
        deliveryClerk.setAccount(account);
        deliveryClerk.setAddress(address);

        deliveryClerk.setCreated(new Date());
        deliveryClerk.setDisState(1);
        deliveryClerk.setIsPayment(0);
        deliveryClerk.setBail(BigDecimal.valueOf(0));
//        deliveryClerk.setDisType(1);
        deliveryClerk.setFontCard(fontCard);
        deliveryClerk.setHandheldPhotos(handheldPhotos);
        deliveryClerk.setHeadPic("");
        deliveryClerk.setIdentityCardNum(identityCardNum);
        deliveryClerk.setName(name);
        deliveryClerk.setPwd(MD5Util.md5(pwd));
        deliveryClerk.setReverseCrad(reverseCrad);
        deliveryClerk.setIsOpen(2);
        deliveryClerk.setCityId(cityId);
        deliveryClerk.setMinId(cityId);
        deliveryClerk.setBalance(new BigDecimal(0));
        if (!handheldPhotos.equals("")) {
            deliveryClerk.setIsCertification(1);
            deliveryClerk.setIsCertificate(2);
        } else {
            deliveryClerk.setIsCertificate(0);
            deliveryClerk.setIsCertification(0);
        }
//        if(areaId!=0){
//            deliveryClerk.setAreaId(areaId);
//            deliveryClerk.setMinId(areaId);
//        }else if(cityId!=0){
//            deliveryClerk.setCityId(cityId);
//            deliveryClerk.setMinId(cityId);
//        }else {
//            deliveryClerk.setProvinceId(provinceId);
//            deliveryClerk.setMinId(provinceId);
//        }
        Long id = deliveryClerkDao.save(deliveryClerk);
        trendService.saveUser(account, pwd, id.intValue(), name, account, "", 3);
        map.put("id", id);
//        String token = TokenUtils.putValue(deliveryClerk.toMap(), 30);
        String token = trendService.getToken(id.intValue(), 3).get("accessToken").toString();
        map.put("token", token);
//        map.put("isAuth", deliveryClerk.getIsCertificate());
        map.put("isAuth", deliveryClerk.getIsCertification());
        map.put("cityId", deliveryClerk.getCityId());
        map.put("isOpen", deliveryClerk.getIsOpen());
        deliveryClerkDao.updateLastLoginDate(id.intValue());
        return map;
    }

    /**
     * 忘记密码修改密码
     *
     * @param account 账号
     * @param newPwd  新密码
     * @return
     */
    @Override
    public boolean updateForgetPwd(String account, String newPwd) {
        DeliveryClerk deliveryClerk = deliveryClerkDao.getDeliveryByPhone(account);
        trendService.updateInfo(deliveryClerk.getId(), deliveryClerk.getAccount(),
                MD5Util.md5(newPwd), deliveryClerk.getAccount(), 3, deliveryClerk.getName(), deliveryClerk.getHeadPic(), "男");
        return deliveryClerkDao.updateForgetPwd(account, MD5Util.md5(newPwd)) > 0;
    }

    /**
     * 验证密码
     *
     * @param deliveryClerkId 商家编号
     * @param pwd             密码
     * @return
     */
    @Override
    public boolean checkPwd(Integer deliveryClerkId, String pwd) throws ServiceException {
        DeliveryClerk deliveryClerk = getDeliveryClerkById(deliveryClerkId);
        if (!deliveryClerk.getPwd().equals(MD5Util.md5(pwd))) {
            throw new ServiceException("密码不正确");
        }
        return true;
    }

    /**
     * 修改密码
     *
     * @param deliveryClerkId 配送员编号
     * @param pwd             密码
     * @param surePwd         确认密码
     * @return
     */
    @Override
    public boolean updatePwd(Integer deliveryClerkId, String pwd, String surePwd) throws ServiceException {
        DeliveryClerk deliveryClerk = getDeliveryClerkById(deliveryClerkId);
//        if (!pwd.equals(surePwd)) {
//            throw new ServiceException("两次密码不一致");
//        }
        trendService.updateInfo(deliveryClerk.getId(), deliveryClerk.getAccount(),
                MD5Util.md5(pwd), deliveryClerk.getAccount(), 3, deliveryClerk.getName(), deliveryClerk.getHeadPic(), "男");
        return deliveryClerkDao.updatePwd(deliveryClerkId, MD5Util.md5(pwd)) > 0;
    }

    /**
     * 根据配送员编号获取配送员信息
     *
     * @param deliveryClerkId 配送员编号
     * @return
     */
    @Override
    public Map<String, Object> getDeliveryInfoById(Integer deliveryClerkId) throws ServiceException {
        if (deliveryClerkId == 0) {
            throw new ServiceException("配送员信息不存在");
        }
        Map<String, Object> map = Optional.fromNullable(deliveryClerkDao.getDeliveryInfoById(deliveryClerkId)).or(new HashMap<String, Object>());
        return map;
    }

    /**
     * 修改配送员信息
     * 实名认证的名字不能修改
     *
     * @param deliveryClerkId 配送员编号
     * @param headPic         头像
     * @return
     */
    @Override
    public boolean updateInfoById(Integer deliveryClerkId, String headPic, String name) throws ServiceException {
        if (deliveryClerkId == 0) {
            throw new ServiceException("配送员信息不存在");
        }
        DeliveryClerk deliveryClerk = deliveryClerkDao.getEntityById(deliveryClerkId);
        trendService.updateInfo(deliveryClerk.getId(), deliveryClerk.getAccount(),
                deliveryClerk.getPwd(), deliveryClerk.getAccount(), 3, name, headPic, "男");
        return deliveryClerkDao.updateInfoById(deliveryClerkId, headPic, name);
    }

    /**
     * 变更手机号
     * 1.旧手机号获取验证码
     * 2.旧手机号验证验证码
     * 3.新手机号获取验证码
     * 4.新手机号验证验证码
     * 5.修改手机号
     *
     * @param deliveryClerkId 配送员编号
     * @param code            验证码
     * @param phone           新手机号
     * @return
     */
    @Override
    public boolean changePhone(Integer deliveryClerkId, String code, String phone) throws ServiceException {
        if (deliveryMsgService.checkForeignPwdCode(phone, code)) {
            return deliveryClerkDao.changePhone(deliveryClerkId, phone);
        }
        return false;
    }

    /**
     * 实名认证
     *
     * @param deliveryClerkId 配送员编号
     * @param identityCardNum 身份证号
     * @param fontCard        身份证正面
     * @param reverseCrad     身份证反面
     * @param handheldPhotos  手持身份证
     * @return
     */
    @Override
    public boolean realNameAuth(String name, Integer deliveryClerkId, String identityCardNum, String fontCard, String reverseCrad, String handheldPhotos) throws ServiceException {
        DeliveryClerk deliveryClerk = getDeliveryClerkById(deliveryClerkId);
        if (deliveryClerk.getIsCertification() == 1) {
            throw new ServiceException("您已经实名认证过了");
        }
        return deliveryClerkDao.realNameAuth(name, deliveryClerkId, identityCardNum, fontCard, reverseCrad, handheldPhotos, 1) > 0;
    }

    /**
     * 根据编号获取账号
     *
     * @param deliveryIds 编号
     * @return
     */
    @Override
    public List<String> getDeliveryClerkAccountsByIds(List<Integer> deliveryIds) {
        List<String> strs = new ArrayList<String>();
        List<Map<String, Object>> maps = deliveryClerkDao.getDeliveryClerkAccountsByIds(deliveryIds);
        if (maps != null && maps.size() > 0) {
            for (Map<String, Object> map : maps) {
                String account = map.get("account").toString();
                strs.add(account);
            }
        }
        return strs;
    }

    /**
     * 上传经纬度
     *
     * @param deliveryId 配送员编号
     * @param cityId     城市编号
     * @param lat        纬度
     * @param lng        经度
     * @return
     */
    @Override
    public boolean uploadLatLng(Integer deliveryId, Integer cityId, String lat, String lng) {
        return DeliveryUtils.uploadLatLng(deliveryId, cityId, lat, lng);
    }

    /**
     * 查询认证
     *
     * @param startCreate
     * @param endCreate
     * @param startTime
     * @param
     * @param cityId
     * @param nowPage
     * @param pageSize    @return
     */
    @Override
    public Page queryAuthentication(String startCreate, String endCreate, String startTime, String endTime, String name, Integer cityId, int nowPage, int pageSize) {
        return deliveryClerkDao.queryAuthentication(startCreate, endCreate, startTime, endTime, name, cityId, nowPage, pageSize);
    }

    /**
     * 查询未认证
     * <p>
     * /**
     * 查询未认证
     *
     * @param name
     * @param
     * @param
     * @param cityId
     * @param nowPage
     * @param pageSize @return
     */
    @Override
    public Page queryNoAuthentication(String name, String startCreate, String endCreate, String startTime, String endTime, Integer cityId, int nowPage, int pageSize) {
        return deliveryClerkDao.queryNoAuthentication(name, startCreate, endCreate, startTime, endTime, cityId, nowPage, pageSize);
    }

    /**
     * 获取实名认证信息
     *
     * @param id 配送员编号
     * @return
     */
    @Override
    public Map<String, Object> getRealNameAuthInfo(Integer id) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        DeliveryClerk deliveryClerk = getDeliveryClerkById(id);
        map.put("name", deliveryClerk.getName());
        map.put("id", id);
        map.put("identityCardNum", deliveryClerk.getIdentityCardNum());
        map.put("fontCard", deliveryClerk.getFontCard());
        map.put("reverseCrad", deliveryClerk.getReverseCrad());
        map.put("handheldPhotos", deliveryClerk.getHandheldPhotos());
        map.put("isCertificate", deliveryClerk.getIsCertificate());
        map.put("isCertification", deliveryClerk.getIsCertification());
        return map;
    }

    /**
     * 修改是否接单状态
     *
     * @param deliveryId 配送员编号
     * @param isOpen     是否接单
     *                   1：接单
     *                   2：停止接单
     * @return
     */
    @Override
    public boolean updateIsOpen(Integer deliveryId, Integer isOpen) throws ServiceException {
        //判断是否有未完成的订单
        List<Map<String, Object>> maps = orderService.findDeliveryOrderByState(deliveryId, 1);
        if (maps != null && maps.size() > 0) {
            throw new ServiceException("您还有未完成的订单,请先完成后再收工");
        }
        return deliveryClerkDao.updateIsOpen(deliveryId, isOpen) > 0;
    }

    /**
     * 配送员通过认证
     *
     * @param id
     * @param isCertificate
     * @return
     */
    @Override
    public int throughDispatcher(Integer id, Integer isCertificate) {
        return deliveryClerkDao.throughDispatcher(id, isCertificate);
    }

    @Override
    public boolean updateDeliverBlance(int disId, BigDecimal add) {
        return deliveryClerkDao.updateDeliverBlance(disId, add);
    }

    /**
     * 功能描述:
     * 查询保证金的信息
     *
     * @param deliveryId 配送员编号
     * @return:
     * @auther: wsl
     * @date: 2019/2/27 14:17
     */
    @Override
    public Map<String, Object> getKetubbah(Integer deliveryId) {
        Map<String, Object> map = new HashMap<>(1);
        Map<String, Object> value = paramsService.getParamsValue(39, 39);
        double bailMoney = Double.parseDouble(value.get("value").toString());
        DeliveryClerk delivery = deliveryClerkDao.getEntityById(deliveryId);
        map.put("bailMoney", bailMoney);
        map.put("isPayment", delivery.getIsPayment());
        map.put("deliveryBail", delivery.getBail());
        map.put("payMoney", delivery.getBail().subtract(BigDecimal.valueOf(bailMoney)));
        return map;
    }

    @Override
    public List<Map<String, Object>> getKetubbahList(Integer deliveryId, Integer nowPage, Integer pageSize) {
        return deliveryClerkDao.getKetubbahList(deliveryId, nowPage, pageSize);
    }

    @Override
    public Map<String, Object> payBail(Integer deliveryId, double payBail, double payType) {
        Map<String, Object> map = new HashMap<>(1);
        DeliveryClerk deliveryClerk = deliveryClerkDao.getEntityById(deliveryId);
        String kid = KidUtils.getKKid();
        String title = deliveryClerk.getName() + "付款：" + payBail + "元";
        if (payType == 1) {
            //支付宝
            //这里传的是支付订单编号
            String aplipay = AppPay.createPay(title, kid, title, payBail);
            map.put("pay", aplipay);
        } else if (payType == 2) {
            int price = BigDecimal.valueOf(payBail).multiply(BigDecimal.valueOf(100)).intValue();
            WeixinPay weixinPay = new com.weixin.pay.api.AppPay();
            PayInfo payInfo = new PayInfo();
            payInfo.setBody(title);
            payInfo.setTradeNo(kid);
            payInfo.setSubject(title);
            payInfo.setPrice(price);
            payInfo.loadWxConfig("wxc288f9db783b396b");
            weixinPay.setPayInfo(payInfo);
            map = weixinPay.createPay();
            System.out.println("支付信息:" + map.toString());
        }
        return map;
    }

    /**
     * 功能描述
     * 配送员使用手册
     *
     * @param:
     * @return:
     * @auther: wsl
     * @date: 2019/3/2 10:58
     */
    @Override
    public List<Map<String, Object>> findGuide() {
        return deliveryClerkDao.findGuide();
    }
}
